// pages/login/index.ts
import { wxLogin, ModUser, GetUserPhone, getUserInfo } from '/../../api/index'
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageHeight: app.globalData.pageHeight,
    showOverlay: false,
    fromUrl: ""
  },
  goBack() {
    let currentPages = getCurrentPages()
    wx.navigateBack()
  },
  bindGetUserInfo(e) {
    console.log(e);
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      wx.setStorageSync('userInfo', e.detail.userInfo);
      let that = this;
      wx.login({
        success(res) {
          if (res.code) {
            app.globalData.code = res.code
            //发起网络请求
            wxLogin({
              Code: res.code
            })
              .then(res => {
                console.log(res);
                app.globalData.token = res.Data.Token
                wx.setStorageSync('token', res.Data.Token)
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 1000
                });
                that.setData({
                  showOverlay: true
                })
              })
              .catch(error => {
                wx.showToast({
                  title: '登录失败,请重试',
                  icon: 'error',
                  duration: 1000
                })
                console.log(error);
              });

          } else {
            console.log('登录失败！' + res.errMsg)
          }


        }
      })
    }
  },
  // 获取用户手机号
  bindGetPhoneNumber(eventhandle) {
    console.log(eventhandle);
    console.log(GetUserPhone);
    // if (!eventhandle.detail.code) {
    //   wx.showToast({
    //     title: '登录失败',
    //     icon: 'error',
    //     duration: 2000
    //   })
    //   setTimeout(() => {
    //     wx.navigateBack()
    //   }, 2000);
    //   return
    // }

    this.login(eventhandle.detail.code)


  },
  async login(phoneCode) {
    try {
      await new Promise((resolve, reject) => {
        wx.login({
          success(res) {
            app.globalData.code = res.code
            resolve(true)
          }
        })
      })
      let loginInfo = await wxLogin({ Code: app.globalData.code })
      app.globalData.token = loginInfo.Data.Token
      wx.setStorageSync('token', loginInfo.Data.Token)
      let phoneData = await GetUserPhone({
        Code: phoneCode
      })
      let userInfo;
      userInfo = await getUserInfo(phoneData.Data)
      if (!userInfo) {
        await this.upDateUserInfo(phoneData.Data)
        userInfo = await getUserInfo(phoneData.Data)
      }
      wx.setStorageSync('userInfo', userInfo)
      wx.setStorageSync('phone', phoneData.Data)
      app.globalData.userInfo = userInfo
      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1000
      })
      setTimeout(() => {
        console.log("调试：",this.data.fromUrl);
        
        if (this.data.fromUrl && this.data.fromUrl != 'undefined') {
          wx.redirectTo({
            url: `/${this.data.fromUrl}`
          })
        } else {
          wx.navigateBack()
        }
      }, 1000);
    } catch (error) {
      wx.removeStorageSync('token')
      wx.showToast({
        title: '登录出错',
        icon: 'error',
        duration: 2000
      })
    }
  },
  // 更新登录用户数据
  async upDateUserInfo(phone) {
    let params = {
      "Id": "",
      "UserName": "",
      "Password": '',
      "Nickname": '',
      "CompanyName": "",
      "Email": "",
      "MobilePhone": phone,
      "Status": 1,
      "UserType": 0,
      "HeaderImg": ''
    }
    return await ModUser(params)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    let fromUrl = decodeURIComponent(options.fromUrl);
    this.setData({
      fromUrl: fromUrl
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})